//
//  picRecodeViewController.m
//  picRecodeDemo
//
//  Created by glendale on 13-6-18.
//  Copyright (c) 2013年 glendale. All rights reserved.
//

#import "picRecodeViewController.h"

#import "UIViewController+MJPopupViewController.h"
#import "recordViewController.h"

#import "mm_preViewPicturesViewController.h"
#import "mm_preViewRecordViewController.h"
#import "PhotoListViewController.h"
#import "PhotoModel.h"

#import <AVFoundation/AVFoundation.h>

@interface picRecodeViewController ()

/** 凹陷 */
@property(nonatomic,strong)NSMutableDictionary *ADefectDic;
/** 掉漆 */
@property(nonatomic,strong)NSMutableDictionary *DDefectDic;
/** 划痕 */
@property(nonatomic,strong)NSMutableDictionary *HDefectDic;
/** 裂纹 */
@property(nonatomic,strong)NSMutableDictionary *LDefectDic;
/** 破损 */
@property(nonatomic,strong)NSMutableDictionary *PDefectDic;
/** 锈蚀 */
@property(nonatomic,strong)NSMutableDictionary *XDefectDic;

@property(nonatomic,copy)NSString *curDefectStr;

@property(nonatomic,strong)UILabel *curMarkLbl;

@property(nonatomic, weak)IBOutlet UIButton *ABtn;
@property(nonatomic, weak)IBOutlet UIButton *DBtn;
@property(nonatomic, weak)IBOutlet UIButton *HBtn;
@property(nonatomic, weak)IBOutlet UIButton *LBtn;
@property(nonatomic, weak)IBOutlet UIButton *PBtn;
@property(nonatomic, weak)IBOutlet UIButton *XBtn;
@property(nonatomic,strong)NSArray *defectTypeButtons;

@property (weak, nonatomic) IBOutlet UIButton *cameraBtn;
@property (weak, nonatomic) IBOutlet UIButton *addDefectBtn;

/** 图片预览 */
@property (weak, nonatomic) IBOutlet UIButton *prePictureBtn;

@end

@implementation picRecodeViewController

@synthesize scrollViewDis = _scrollViewDis;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.recordViewCon = [[recordViewController alloc] init];
        [self.recordViewCon prepareForRecord];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    UIGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(SelectTap:)];
    recognizer.delegate =self;
    [self.TapImgView setUserInteractionEnabled:self.canEdit];
    [self.TapImgView addGestureRecognizer:recognizer];
    
    [self.scrollViewDis setContentSize:CGSizeMake(self.scrollViewDis.frame.size.width, 1150)];
    
    [self createSubViewDis];
    
    //当进入这个界面的时候要将以前的所有标记过的图标进行添加
    [self addThePreIcon];
    
    self.defectType = @"A";
    
    //刷新子视图 列表
    [subViewDis setNeedsDisplay];
    [self setControlDisableIfNotEdit];
}

/** 如果是查看模式设置控件不可编辑 */
-(void)setControlDisableIfNotEdit{
    if (!self.canEdit) {
        [self.defectTypeButtons makeObjectsPerformSelector:@selector(setEnabled:) withObject:NO];
        self.cameraBtn.enabled = false;
        self.addDefectBtn.enabled = false;
    }
}

-(void)SelectTap:(UITapGestureRecognizer*)recognizer{
    
    NSString *idIndexStr = [self getMaxDefectTypeNumWithTypestr:self.defectType];
    NSString *typeName = [self getTypeNameWithTypeStr:self.defectType];

    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(self.currentPoint.x-15, self.currentPoint.y-15, 30, 30)];
    lbl.text = idIndexStr;
    lbl.textColor = [UIColor blueColor];
    lbl.font = [UIFont fontWithName:@"ArialMT" size:16];
    lbl.backgroundColor = [UIColor clearColor];
    [self.TapImgView addSubview:lbl];
    self.curDefectStr = idIndexStr;
    self.curMarkLbl = lbl;
    popEditViewDis = nil;
    popEditViewDis = [[mm_popupEditViewController alloc] initWithNibName:@"mm_popupEditViewController" bundle:nil];
    
    popEditViewDis.bianhaoDisLbl.text = idIndexStr;
    popEditViewDis.leixingDisLbl.text = typeName;
    popEditViewDis.isNewOperation = YES;
    popEditViewDis.currentPoint = self.currentPoint;
    
    [self presentPopupViewController:popEditViewDis animationType:MJPopupViewAnimationFade];
}

#pragma mark - 弹出框代理方法
-(void)doItBeforeDismiss
{
    NSLog(@"doItBeforeDismiss !!!");
}

#pragma mark - 手势代理方法

//设置可点击的区域
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    
    CGPoint currentPoint = [touch locationInView:self.TapImgView];

    if ((!CGRectContainsPoint(CGRectMake(0, 0, 208, 148), currentPoint))&(!CGRectContainsPoint(CGRectMake(624, 0, 208, 148), currentPoint))&(!CGRectContainsPoint(CGRectMake(624, 298, 208, 148), currentPoint))&(!CGRectContainsPoint(CGRectMake(0, 298, 208, 148), currentPoint))){
        
        NSLog(@"currentPoint=xx=%f＝＝＝Y==%f",currentPoint.x,currentPoint.y);
        self.currentPoint = currentPoint;
        return YES;
    }
    return NO;
}

- (IBAction)ABtnSelect:(UIButton *)sender {
    [self setUnSelectedButButton:sender type:@"A"];
}

- (IBAction)DBtnSelect:(UIButton *)sender {
    [self setUnSelectedButButton:sender type:@"D"];
}

- (IBAction)HBtnSelect:(UIButton *)sender {
    [self setUnSelectedButButton:sender type:@"H"];
}

- (IBAction)PBtnSelect:(UIButton *)sender {
    [self setUnSelectedButButton:sender type:@"P"];
}

- (IBAction)LBtnSelect:(UIButton *)sender {
    [self setUnSelectedButButton:sender type:@"L"];
}

- (IBAction)XBtnSelect:(UIButton *)sender {
    [self setUnSelectedButButton:sender type:@"X"];
}

-(void)setUnSelectedButButton:(UIButton *)btn type:(NSString *)type{
    [self.defectTypeButtons makeObjectsPerformSelector:@selector(setSelected:) withObject:false];
    btn.selected = YES;
    self.defectType = type;
}

//拍照按钮的回调方法
-(IBAction)popBtn:(id)sender{
    
//    inputPicViewController *inputVc = [[inputPicViewController alloc] initWithNibName:@"inputPicViewController" bundle:nil];
//    [self presentPopupViewController:inputVc animationType:MJPopupViewAnimationFade];
    
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        //先检查相机可用是否
        BOOL cameraIsAvailable = [self checkCamera];
        if (YES == cameraIsAvailable) {
            [self presentViewController:picker animated:YES completion:nil];
        }else {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请在iPhone的“设置-隐私-相机”选项中，允许本应用程序访问你的相机。" delegate:self cancelButtonTitle:@"好，我知道了" otherButtonTitles:nil];
            [alert show];
        }
        
    }
}
//检查相机是否可用
- (BOOL)checkCamera
{
    NSString *mediaType = AVMediaTypeVideo;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:mediaType];
    if(AVAuthorizationStatusRestricted == authStatus ||
       AVAuthorizationStatusDenied == authStatus)
    {
        //相机不可用
        return NO;
    }
    //相机可用
    return YES;
}
- (IBAction)recodeBtn:(id)sender
{
    [self.recordViewCon recordOrStop:sender];
    
    //如果是停止状态表明录音完成，那就要进行.caf转换成.mp3
    if (!self.recordViewCon.recording)
    {
        //开一个子线程进行录音格式转换
        [NSThread detachNewThreadSelector:@selector(audioToMp3) toTarget:self withObject:nil];
    }
}

- (IBAction)playBtn:(id)sender
{
//    [self.recordViewCon playback:sender];
}

- (IBAction)backSelect:(id)sender {
    
    [self.navigationController popViewControllerAnimated:YES];
}

-(UIImage *)resizeCImage:(UIImage *)image toSize:(CGSize)size
{
    float width = size.width;
    float height = size.height;
    
    NSLog(@"WIDTH IN RESIZED FUN ====%f",width);
    
    UIGraphicsBeginImageContext(size);
    
    float x = 0.0f;
    float y = 0.0f;
   
    
    CGRect rect = CGRectMake(x, y, width, height);
    
    [image drawInRect: rect];
    
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return newImage;
}

#pragma mark - 保存图片至沙盒
- (void) saveImage:(UIImage *)currentImage withName:(NSString *)imageName
{
    
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    // 获取沙盒目录
    
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    // 将图片写入文件
    
    [imageData writeToFile:fullPath atomically:NO];
}

//-(void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation
//{
//    if (fromInterfaceOrientation == UIInterfaceOrientationLandscapeRight)
//    {
//        NSLog(@"home键向左！");
//    }
//}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    //NSLog(@"%@",info);
    
    [picker setVideoQuality:UIImagePickerControllerQualityTypeHigh];
    
    UIImage *imageimage = [info valueForKey:UIImagePickerControllerOriginalImage];
//    UIImage *image = [picRecodeViewController imageWithImageSimple:imageimage scaledToSize:CGSizeMake(320, 240)];
    
    mm_picRecodeDataModel *modelIns = [mm_picRecodeDataModel sharedModelIns];
    
    PhotoModel *pm = [[PhotoModel alloc]init];
    pm.image = imageimage;
    pm.newImage = YES;
    pm.status = @"A";
    if (!modelIns.arrForNewImage) {
        modelIns.arrForNewImage = [NSMutableArray array];
    }
    pm.fileId = [NSString stringWithFormat:@"newImage%d",modelIns.arrForNewImage.count];
    [modelIns.arrForNewImage addObject:pm];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}

//压缩图片
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    //Create a graphics image context
    UIGraphicsBeginImageContext(newSize);
    //Tell the old image to draw in this new context, with the desired
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    //Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    //End the context
    UIGraphicsEndImageContext();
    return newImage;
}

-(NSString*)imageFileTextPath:(NSString*)imageName{
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *imgStr = [NSString stringWithFormat:@"/%@",imageName];
    NSLog(@"path==%@",[documentPath stringByAppendingPathComponent:imgStr]);
    
    return [documentPath stringByAppendingPathComponent:imgStr];
}

- (BOOL)writeImage:(UIImage*)image toFileAtPath:(NSString*)aPath{
    if ((image == nil) || (aPath == nil) || ([aPath isEqualToString:@""]))
        return NO;
    @try
    {
        
        NSData *imageData = nil;
        NSString *ext = [aPath pathExtension];
        if ([ext isEqualToString:@"png"])
        {
            imageData = UIImagePNGRepresentation(image);
        }
        else
        {
            // the rest, we write to jpeg
            // 0. best, 1. lost. about compress.
            NSLog(@"++++++++");
            imageData = UIImageJPEGRepresentation(image, 1.0);
            
        }
        
        if ((imageData == nil) || ([imageData length] <= 0))
            return NO;
        
        [imageData writeToFile:aPath atomically:NO];
        return YES;
    }
    @catch (NSException *e)
    {
        NSLog(@"create thumbnail exception.");
    }
    return NO;
}

#pragma mark - 创建子视图用于显示

-(void)createSubViewDis
{
    subViewDis = [[mm_subViewForPicRecode alloc] initWithFrame:CGRectMake(11, 660, 990, 400)];
    subViewDis.backgroundColor = [UIColor clearColor];
    subViewDis.nRowSel = -1;
    subViewDis.delegate = self;
    subViewDis.canEdit = self.canEdit;
    [self.scrollViewDis addSubview:subViewDis];
}

#pragma mark - 按钮回调方法

- (IBAction)editBtnPressed:(UIButton *)sender
{
    NSLog(@"editBtnPressed !!!");
    
    [subViewDis.tableViewDis setEditing:!subViewDis.tableViewDis.editing animated:YES];
}

#pragma mark - 重写方法

-(void)dismissPopupViewControllerWithanimationType:(MJPopupViewAnimation)animationType
{
    BOOL flag =[popEditViewDis saveData];
    if (!flag) {
        if (popEditViewDis.isNewOperation&&popEditViewDis.numsText.text.length<=0) {//如果是新增并且没有填写数量
            [self.curMarkLbl removeFromSuperview];//移除标记
            self.curDefectStr = nil;
            [super dismissPopupViewControllerWithanimationType:animationType];
        }
        return;
    }
    [super dismissPopupViewControllerWithanimationType:animationType];
    [subViewDis setNeedsDisplay];
    if (popEditViewDis.isNewOperation){//如果是新增
        //新标记加入相应的数组
        [self addDefectToArrWithType:self.curDefectStr lable:self.curMarkLbl];//加入相应的数组
    }
    
    //调用代理方法
    if ([self.delegate respondsToSelector:@selector(defectListChanged)]) {
        [self.delegate defectListChanged];
    }
}


//添加以前标记过的图标
-(void)addThePreIcon
{
    //在添加图标之前，先将模型类的数据进行初始化
    MainMenuDataModel *modelMainMenuIns = [MainMenuDataModel sharedMainMenuDataModel];
    NSArray *outcheckList = modelMainMenuIns.arrOutCheck;

    for (int i = 0; i<[modelMainMenuIns.arrOutCheck count]; i++)
    {
        NSDictionary *data = outcheckList[i];
        NSString *numStr = data[MM_OUT_CHECK_OUT_CHECK_NUMBER_KEY_STR_];
        NSString *strPoint = data[MM_OUT_CHECK_POINT_KEY_STR_];
        NSRange range = [strPoint rangeOfString:@","];
        
        if (range.location == NSNotFound)
        {
            continue;
        }
        
        CGFloat cgPointX = [[strPoint substringToIndex:range.location] floatValue]*2.0;
        CGFloat cgPointY = [[strPoint substringFromIndex:range.location+1] floatValue]*2.0;

        UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(cgPointX-10, cgPointY-10, 20, 20)];
        lbl.text = data[MM_OUT_CHECK_OUT_CHECK_NUMBER_KEY_STR_];
        lbl.textColor = [UIColor redColor];
        lbl.font = [UIFont systemFontOfSize:13];
        lbl.backgroundColor = [UIColor clearColor];
        [self.TapImgView addSubview:lbl];
        [self addDefectToArrWithType:numStr lable:lbl];//加入数组中
    
    }

}

-(void)addDefectToArrWithType:(NSString *)typeStr lable:(UILabel *)label{
    NSRange range = {0,1};
    NSString *defectType = [typeStr substringWithRange:range];
    if ([defectType isEqualToString:@"A"]) {
        [self.ADefectDic setObject:label forKey:typeStr];
    }else if ([defectType isEqualToString:@"D"]){
        [self.DDefectDic setObject:label forKey:typeStr];
    }else if ([defectType isEqualToString:@"H"]){
        [self.HDefectDic setObject:label forKey:typeStr];
    }else if ([defectType isEqualToString:@"L"]){
        [self.LDefectDic setObject:label forKey:typeStr];
    }else if ([defectType isEqualToString:@"P"]){
        [self.PDefectDic setObject:label forKey:typeStr];
    }else if ([defectType isEqualToString:@"X"]){
        [self.XDefectDic setObject:label forKey:typeStr];
    }
}

#pragma mark - 图片预览 和 录音查看 按钮 回调方法

- (IBAction)preViewPicturesBtnPressed:(UIButton *)sender
{
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    mm_picRecodeDataModel *picDataModel = [mm_picRecodeDataModel sharedModelIns];
    picDataModel.arrForAllCapturePic = nil;//清空
    if (modelIns.arrImageList.count>0) {        
        
        for (NSDictionary *dic in modelIns.arrImageList) {//从数据库获取的图片列表
            if (![self Arr:picDataModel.arrForDeletedImages containsObjec:dic]) {//查找没有被删除的图片
                PhotoModel *pm = [PhotoModel photoModelWithDic:dic];
                [picDataModel.arrForAllCapturePic addObject:pm];
            }
        }
    }
    //加入新图片
    if (picDataModel.arrForNewImage.count) {
        NSRange range = {0,picDataModel.arrForNewImage.count};
        NSIndexSet *indexSet = [NSIndexSet indexSetWithIndexesInRange:range];
        [picDataModel.arrForAllCapturePic insertObjects:picDataModel.arrForNewImage atIndexes:indexSet];
    }
    PhotoListViewController *vc = [[PhotoListViewController alloc]init];
    vc.editOperation = self.canEdit;
    [self.navigationController pushViewController:vc animated:YES];

}

-(BOOL)Arr:(NSArray *)arr containsObjec:(NSDictionary *)dic{
    for (NSDictionary *delectedDic in arr) {
        NSString *itemId = [dic[deletedImageName]stringValue];
        if ([delectedDic[deletedImageName] isEqualToString:itemId]) {
            return true;
        }
    }
    return false;
}

- (IBAction)preViewRecordBtnPressed:(UIButton *)sender
{
    NSLog(@"preViewRecordBtnPressed !!!");
        
    //跳转到录音查看的界面
    mm_preViewRecordViewController *vc = [[mm_preViewRecordViewController alloc] initWithNibName:@"mm_preViewRecordViewController" bundle:nil];
    
    //录音查看的权限
    vc.nLimitOfAuthority = MM_PIC_CAN_UPDATE_;
    
    [self.navigationController pushViewController:vc animated:YES];
}

//将音频文件转换成.mp3格式
//-(void)audioToMp3FromAudioPathOri:(NSString *)audioPathOri toAudioPathMp3:(NSString *)audioPathMp3
//{
//    //进入转换
//    int read, write;
//
//    FILE *pcm = fopen([audioPathOri cStringUsingEncoding:1], "rb");//被转换的文件
//    FILE *mp3 = fopen([audioPathMp3 cStringUsingEncoding:1], "wb");//转换后文件的存放位置
//
//    const int PCM_SIZE = 8192;
//
//    const int MP3_SIZE = 8192;
//
//    short int pcm_buffer[PCM_SIZE*2];
//
//    unsigned char mp3_buffer[MP3_SIZE];
//
//    lame_t lame = lame_init();
//
//    lame_set_in_samplerate(lame, 11025.0);
//
//    lame_set_VBR(lame, vbr_default);
//
//    lame_init_params(lame);
//
//    do {
//
//        read = fread(pcm_buffer, 2*sizeof(short int), PCM_SIZE, pcm);
//
//        if (read == 0)
//
//            write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
//
//        else
//
//            write = lame_encode_buffer_interleaved(lame, pcm_buffer, read, mp3_buffer, MP3_SIZE);
//
//        fwrite(mp3_buffer, write, 1, mp3);
//
//    } while (read != 0);
//
//    lame_close(lame);
//
//    fclose(mp3);
//
//    fclose(pcm);
//}

-(void)audioToMp3
{
    NSString *audioFilePath = [self.recordViewCon soundfileTextPath];
    
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *soundFilePath= [documentPath stringByAppendingPathComponent:@"mm_switch.mp3"];
    
    
    //打印文件路径
    NSLog(@"%@",documentPath);
    
//    [self audioToMp3FromAudioPathOri:audioFilePath toAudioPathMp3:soundFilePath];
    
    //上传mp3音频文件到服务器
    [self uploadMp3FileToServer];
}

//测试接口
-(void)testUpLoad
{
    //test
    
    AppDelegate *myDelegate = [[UIApplication sharedApplication] delegate];
    NSString *currentIp = myDelegate.currentIp;
    NSString *urlString = [NSString stringWithFormat:@"http://%@%@%@.aspx",currentIp,WEBSFILE,MM_ADD_FUNCTION_CHECK_RECORDING_];
    
    NSLog(@"%@",urlString);
    
    urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *serverURL = [NSURL URLWithString:urlString];
    
    //local path
    NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *soundFilePath= [documentPath stringByAppendingPathComponent:@"mm_switch.mp3"];
    
    NSLog(@"%@",soundFilePath);
    
//    NSData *postDataXingCan = [NSData dataWithContentsOfURL:[NSURL URLWithString:soundFilePath]];
    
    //将图片数据转化成 NSInputStream
//    NSInputStream *inputStreamForFile = [NSInputStream inputStreamWithData:postDataXingCan];
    NSInputStream *inputStreamForFile = [NSInputStream inputStreamWithFileAtPath:soundFilePath];
    
    //上传大小
//    NSNumber *contentLength = (NSNumber *)[NSNumber numberWithInteger:[postDataXingCan length]];
    NSNumber *contentLength = (NSNumber *)[[[NSFileManager defaultManager] attributesOfItemAtPath:soundFilePath error:nil] objectForKey:NSFileSize];
    
    //开始拼数据
    NSMutableURLRequest *request;
    request = [NSMutableURLRequest requestWithURL:serverURL];
    [request setHTTPMethod:@"POST"];
    [request setHTTPBodyStream:inputStreamForFile];
    [request setValue:@"audio/mp3" forHTTPHeaderField:@"Content-Type"];
    [request setValue:[contentLength description] forHTTPHeaderField:@"Content-Length"];
    
    // 请求
    // self.aSynConnection = [NSURLConnection connectionWithRequest:request delegate:self];
    NSURLResponse *urlResponse;
    NSData *returnData=[NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:nil];
    NSString *result = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    [[NSNotificationCenter defaultCenter] postNotificationName:MM_ADD_FUNCTION_CHECK_RECORDING_ object:returnData];
    NSLog(@"rrrrr=%@",result);
}

//上传mp3录音文件
-(void)uploadMp3FileToServer
{
    [self testUpLoad];
}

//注册消息
-(void)addAllObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addImgToServer:) name:MM_ADD_OUT_CHECK_PIC_ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAudioToServer:) name:MM_ADD_FUNCTION_CHECK_RECORDING_ object:nil];
}

//移除消息
-(void)removeAllObserver
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//图片上传接口的回调方法
-(void)addImgToServer:(NSNotification *)notification
{
    /*
     {"picName":"20130830210757.jpg","error_code":0,"error_msg":""}
     */
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    NSLog(@"%@",theJson);
    
    NSString *picNameStr = [theJson objectForKey:@"picName"];
    NSString *errorCodeStr = [NSString stringWithFormat:@"%@",[theJson objectForKey:@"error_code"]];
    NSString *errorMsgStr = [theJson objectForKey:@"error_msg"];
    /*
     （1）如果上传成功，获取返回的图片名称，并且将该名称添加入存放图片名称的数组；否则提示错误信息，return；
     */
    
    /*
     "imageNameList"://imageName改为imageNameList
     [
     {"imageName":"2013.jpg"},
     {"imageName":"2014.jpg"}
     ],
     */
    
    if (![errorCodeStr isEqualToString:@"0"])
    {
        //提示保存失败，return
        
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"图片保存失败" message:errorMsgStr delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    if (0 == [modelIns.arrImageList count])
    {
        modelIns.arrImageList = [NSMutableArray array];
    }
    else
    {
        modelIns.arrImageList = [NSMutableArray arrayWithArray:modelIns.arrImageList];
    }
    NSDictionary *dicTmp = [NSDictionary dictionaryWithObjectsAndKeys:picNameStr,@"imageName", nil];
    [modelIns.arrImageList addObject:dicTmp];
    
    //将图片列表添加进数组中
    modelIns.dicJobSheetMsg = [NSMutableDictionary dictionaryWithDictionary:modelIns.dicJobSheetMsg];
    [modelIns.dicJobSheetMsg setObject:modelIns.arrImageList forKey:@"imageNameList"];
    
//    NSLog(@"modelIns.dicJobSheetMsg = %@",[modelIns.dicJobSheetMsg objectForKey:@"imageNameList"]);
//    NSLog(@"modelIns.dicJobSheetMsg = %@",modelIns.dicJobSheetMsg);

}

//录音上传接口的回调方法
-(void)addAudioToServer:(NSNotification *)notification
{
    /*
     {"recordName":"20130902153343.mp3","error_code":0,"error_msg":""}
     */
    NSDictionary *theJson = [NSJSONSerialization JSONObjectWithData:(NSData*)notification.object options:NSJSONReadingMutableLeaves error:Nil];
    NSLog(@"%@",theJson);
    
    /*
     （1）如果上传失败，提示 失败信息，return；
     （2）如果上传成功，将返回的录音名称加入录音的数据模型中
     */
    
    //（1）如果上传失败，提示 失败信息，return；
    if ([[theJson objectForKey:@"error_code"] integerValue] != 0)
    {
        UIAlertView *alerVeiw = [[UIAlertView alloc] initWithTitle:@"提示信息" message:[theJson objectForKey:@"error_msg"] delegate:self cancelButtonTitle:@"我知道了" otherButtonTitles:nil, nil];
        [alerVeiw show];
        
        return;
    }
    
    //（2）如果上传成功，将返回的录音名称加入录音的数据模型中
    MainMenuDataModel *modelIns = [MainMenuDataModel sharedMainMenuDataModel];
    
    if ([modelIns.arrRecodeList count] == 0)
    {
        modelIns.arrRecodeList = [NSMutableArray array];
    }
    else
    {
        modelIns.arrRecodeList = [NSMutableArray arrayWithArray:modelIns.arrRecodeList];
    }
    [modelIns.arrRecodeList addObject:[NSDictionary dictionaryWithObjectsAndKeys:[theJson objectForKey:@"recordName"],MM_RECORD_LIST_RECORD_NAME_KEY_STR_, nil]];
    
    //@"recodeName" maybe is @"recordName"
}

//缺陷点编辑
- (IBAction)editFaultyPointBtnPressed:(UIButton *)sender
{
    if (subViewDis.nRowSel<0) {
        UIAlertView *tip = [[UIAlertView alloc] initWithTitle:@"提示信息" message:@"请选择一行数据" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [tip show];
        return;
    }
    MainMenuDataModel *mainModel = [MainMenuDataModel sharedMainMenuDataModel];
    NSDictionary *dic = mainModel.arrOutCheck[subViewDis.nRowSel];
    popEditViewDis = nil;
    popEditViewDis = [[mm_popupEditViewController alloc] initWithNibName:@"mm_popupEditViewController" bundle:nil];
    
    popEditViewDis.bianhaoDisLbl.text = dic[MM_OUT_CHECK_OUT_CHECK_NUMBER_KEY_STR_];
    popEditViewDis.leixingDisLbl.text = dic[MM_OUT_CHECK_CHECK_ITEM_KEY_STR_];
    popEditViewDis.numsText.text = [dic[MM_OUT_CHECK_DEFECT_COUNT_KEY_STR_]stringValue];
    popEditViewDis.remarksText.text = dic[MM_OUT_CHECK_DEFECT_DESCRIPTION_KEY_STR_];
    popEditViewDis.isNewOperation = false;
    popEditViewDis.selectedRow = subViewDis.nRowSel;
    [self presentPopupViewController:popEditViewDis animationType:MJPopupViewAnimationFade];
}


//将故障点中的所有图片拿出来组成一个行的列表
-(NSArray *)arrPicsInOutCheckList
{
    mm_picRecodeDataModel *picModelIns = [mm_picRecodeDataModel sharedModelIns];
    NSMutableArray *arrFinalList = [NSMutableArray array];
    
    for (int i = 0; i<[picModelIns.arrForAllFaultyObj count]; i++)
    {
        NSArray *arrImageListTmp = [[picModelIns.arrForAllFaultyObj objectAtIndex:i] objectForKey:MM_OUT_CHECK_IMAGE_NAME_LIST_KEY_STR_];
        for (int j = 0; j<[arrImageListTmp count]; j++)
        {
            [arrFinalList addObject:[arrImageListTmp objectAtIndex:j]];
        }
    }
    
    return arrFinalList;
}

//通过传入的索引 i（i为故障点中对应的照片索引） 返回故障点中图片的名字STR
-(NSString *)returnImageNameFromOutCheckListByImageIndex:(NSInteger)indexXingCan
{
    mm_picRecodeDataModel *picModelIns = [mm_picRecodeDataModel sharedModelIns];
    
    NSInteger nCount = 0;
    for (int i = 0; i<[picModelIns.arrForAllFaultyObj count]; i++)
    {
        NSArray *arrImageListTmp = [[picModelIns.arrForAllFaultyObj objectAtIndex:i] objectForKey:MM_OUT_CHECK_IMAGE_NAME_LIST_KEY_STR_];
        for (int j = 0; j<[arrImageListTmp count]; j++)
        {
            if (nCount == indexXingCan)
            {
                return [[[[picModelIns.arrForAllFaultyObj objectAtIndex:i] objectForKey:MM_OUT_CHECK_IMAGE_NAME_LIST_KEY_STR_] objectAtIndex:j] objectForKey:MM_OUT_CHECK_IMAGE_NAME_KEY_STR_];
            }
            nCount ++;
        }
    }
    
    return @"";
}

//弹出缺陷编辑的popUpView
-(void)faultyPointQuitPopUpView:(NSNotification *)notification
{
    _strForQuitPopUpViewFlag = @"quitFromOKBtn";
    
    [self dismissPopupViewControllerWithanimationType:MJPopupViewAnimationFade];
}

#pragma mark - 缺陷数组懒加载
-(NSMutableDictionary *)ADefectDic{
    if (_ADefectDic == nil) {
        _ADefectDic = [NSMutableDictionary dictionary];
    }
    return _ADefectDic;
}

-(NSMutableDictionary *)DDefectDic{
    if (_DDefectDic == nil) {
        _DDefectDic = [NSMutableDictionary dictionary];
    }
    return _DDefectDic;
}

-(NSMutableDictionary *)HDefectDic{
    if (_HDefectDic == nil) {
        _HDefectDic = [NSMutableDictionary dictionary];
    }
    return _HDefectDic;
}

-(NSMutableDictionary *)LDefectDic{
    if (_LDefectDic == nil) {
        _LDefectDic = [NSMutableDictionary dictionary];
    }
    return _LDefectDic;
}
-(NSMutableDictionary *)PDefectDic{
    if (_PDefectDic == nil) {
        _PDefectDic = [NSMutableDictionary dictionary];
    }
    return _PDefectDic;
}

-(NSMutableDictionary *)XDefectDic{
    if (_XDefectDic == nil) {
        _XDefectDic = [NSMutableDictionary dictionary];
    }
    return _XDefectDic;
}

-(NSString *)getMaxDefectTypeNumWithTypestr:(NSString *)typeStr{
    NSRange range = {0,1};
    typeStr = [typeStr substringWithRange:range];
    NSString *numStr = @"";
    int count = 0;
    if ([typeStr isEqualToString:@"A"]) {
        count = [self getMaxCountWithArr:self.ADefectDic.allKeys];
        numStr = [NSString stringWithFormat:@"A%d",count];
    }else if ([typeStr isEqualToString:@"D"]){
        count = [self getMaxCountWithArr:self.DDefectDic.allKeys];
        numStr = [NSString stringWithFormat:@"D%d",count];
    }else if ([typeStr isEqualToString:@"H"]){
        count = [self getMaxCountWithArr:self.HDefectDic.allKeys];
        numStr = [NSString stringWithFormat:@"H%d",count];
    }else if ([typeStr isEqualToString:@"L"]){
        count = [self getMaxCountWithArr:self.LDefectDic.allKeys];
        numStr = [NSString stringWithFormat:@"L%d",count];
    }else if ([typeStr isEqualToString:@"P"]){
        count = [self getMaxCountWithArr:self.PDefectDic.allKeys];
        numStr = [NSString stringWithFormat:@"P%d",count];
    }else if ([typeStr isEqualToString:@"X"]){
        count = [self getMaxCountWithArr:self.XDefectDic.allKeys];
        numStr = [NSString stringWithFormat:@"X%d",count];
    }
    return numStr;
}

-(int)getMaxCountWithArr:(NSArray *)arr{
    if (arr.count) {
        int nCount = 0;
        for (NSString *str in arr) {
            int num = [[str substringFromIndex:1]intValue];
            nCount = nCount >= num ? nCount : num;
        }
        return nCount +1;
    }else{
        return 1;
    }
}

-(NSString *)getTypeNameWithTypeStr:(NSString *)typeStr{
    NSRange range = {0,1};
    typeStr = [typeStr substringWithRange:range];
    NSString *typeName = @"";
    if ([typeStr isEqualToString:@"A"]) {
        typeName = @"凹陷";
    }else if ([typeStr isEqualToString:@"D"]){
        typeName = @"掉漆";
    }else if ([typeStr isEqualToString:@"H"]){
        typeName = @"划痕";
    }else if ([typeStr isEqualToString:@"L"]){
        typeName = @"裂纹";
    }else if ([typeStr isEqualToString:@"P"]){
        typeName = @"破损";
    }else if ([typeStr isEqualToString:@"X"]){
        typeName = @"锈蚀";
    }
    return typeName;
}

-(NSArray *)defectTypeButtons{
    if (_defectTypeButtons == nil) {
        _defectTypeButtons = @[self.ABtn,self.DBtn,self.HBtn,self.LBtn,self.PBtn,self.XBtn];
    }
    return _defectTypeButtons;
}

#pragma mark - mm_subViewForPicRecode代理方法
-(void)deleteData:(NSDictionary *)dic atIndexPath:(NSIndexPath *)indexPath{
    NSString *indexNum = dic[MM_OUT_CHECK_OUT_CHECK_NUMBER_KEY_STR_];
    NSRange range = {0,1};
    NSString *typeStr = [indexNum substringWithRange:range];
    UILabel *markLbl = nil;
    if ([typeStr isEqualToString:@"A"]) {
        markLbl = [self.ADefectDic objectForKey:indexNum];
        [self.ADefectDic removeObjectForKey:indexNum];
    }else if ([typeStr isEqualToString:@"D"]){
        markLbl = [self.DDefectDic objectForKey:indexNum];
        [self.DDefectDic removeObjectForKey:indexNum];
    }else if ([typeStr isEqualToString:@"H"]){
        markLbl = [self.HDefectDic objectForKey:indexNum];
        [self.HDefectDic removeObjectForKey:indexNum];
    }else if ([typeStr isEqualToString:@"L"]){
        markLbl = [self.LDefectDic objectForKey:indexNum];
        [self.LDefectDic removeObjectForKey:indexNum];
    }else if ([typeStr isEqualToString:@"P"]){
        markLbl = [self.PDefectDic objectForKey:indexNum];
        [self.PDefectDic removeObjectForKey:indexNum];
    }else if ([typeStr isEqualToString:@"X"]){
        markLbl = [self.XDefectDic objectForKey:indexNum];
        [self.XDefectDic removeObjectForKey:indexNum];
    }
    [markLbl removeFromSuperview];//移除标记
    
    //调用代理方法
    if ([self.delegate respondsToSelector:@selector(defectListChanged)]) {
        [self.delegate defectListChanged];
    }
}
@end
